package com.mimaxueyuan.disruptor.demo07;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @author: Kevin
 * [每天进步一点点、人生带来大改变...]
 */
public class LongEventMain {

	public static long startTime;

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws InterruptedException {
		// 初始化线程池-用户执行Consumer
		ThreadFactory threadFactory = Executors.defaultThreadFactory();
		// 初始化EventFactory
		LongEventFactory factory = new LongEventFactory();
		// 初始化RingBuffer的大小,必须是2的指数
		int bufferSize = 1024;
		// 初始化Disruptor
		// 默认配置
		// BlockingWaitStrategy waitStrategy = new BlockingWaitStrategy();
		// SleepingWaitStrategy waitStrategy = new SleepingWaitStrategy();
		YieldingWaitStrategy waitStrategy = new YieldingWaitStrategy();
		Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(factory, bufferSize, threadFactory, ProducerType.MULTI, waitStrategy);
		// 指定事件处理器
		disruptor.handleEventsWith(new LongEventHandler1()).handleEventsWith(new LongEventHandler2());
		// 开启Disruptor,开启所有线程
		disruptor.start();
		// 获取RingBuffer
		RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
		// 采用固定模式向RingBuffer中添加事件
		final LongEventProducer producer = new LongEventProducer(ringBuffer);
		producer.onData(1L);
		// 10线程并发下的Disruptor
//		ExecutorService executor1 = Executors.newCachedThreadPool();
//		startTime = System.currentTimeMillis();
//		for (long i = 0; i < 10; i++) {
//			final long vv = i;
//			executor1.submit(new Runnable() {
//				public void run() {
//					try {
//						producer.onData(vv);
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//				}
//			});
//		}

		// 停止所有Consumer
		// disruptor.halt();
		// disruptor.shutdown();
	}

}
